package io.kiki.stack.http.feign.form.multipart;

import feign.codec.EncodeException;
import lombok.val;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * A single-file writer.
 *
 * @author Artem Labazin
 */
public class SingleFileWriter extends AbstractWriter {

    @Override
    public boolean isApplicable(Object value) {
        return value instanceof File;
    }

    @Override
    protected void write(Output output, String key, Object value) throws EncodeException {
        val file = (File) value;
        writeFileMetadata(output, key, file.getName(), null);

        try (InputStream input = new FileInputStream(file)) {
            val buf = new byte[4096];
            int length = input.read(buf);
            while (length > 0) {
                output.write(buf, 0, length);
                length = input.read(buf);
            }
        } catch (IOException ex) {
            val message = String.format("Writing file's '%s' content error", file.getName());
            throw new EncodeException(message, ex);
        }
    }
}
